package com.hcg.distributedtx.config.datasource;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.hcg.distributedtx.config.db.DBConfigHcg;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.hcg.distributedtx.mapper.hcg"/*"com.hcg.distributedtx.hcg"*/,sqlSessionTemplateRef = "hcgSqlSessionTemplate")
public class HcgDataSourceConfig {

    // 配置数据源
    @Bean("hcgDataSource")
    public DataSource hcgDataSource(DBConfigHcg dbConfigHcg) throws Exception{
        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
        mysqlXADataSource.setURL(dbConfigHcg.getJdbc_url());
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
        mysqlXADataSource.setPassword(dbConfigHcg.getPassword());
        mysqlXADataSource.setUser(dbConfigHcg.getUsername());
        mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);

        // 创建 Atomikos 全局事务，并将本地事务注册进去
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
        atomikosDataSourceBean.setUniqueResourceName("hcgDataSource");

        atomikosDataSourceBean.setMinPoolSize(dbConfigHcg.getMinPooSize());
        atomikosDataSourceBean.setMaxPoolSize(dbConfigHcg.getMaxPooSize());
        atomikosDataSourceBean.setMaxLifetime(dbConfigHcg.getMaxLifetime());
        atomikosDataSourceBean.setBorrowConnectionTimeout(dbConfigHcg.getBoorowConnectionTimeout());
        atomikosDataSourceBean.setLoginTimeout(dbConfigHcg.getLoginTimeout());
        atomikosDataSourceBean.setMaintenanceInterval(dbConfigHcg.getMaintenanceInterval());
        atomikosDataSourceBean.setMaxIdleTime(dbConfigHcg.getMaxIdleTime());
        atomikosDataSourceBean.setTestQuery(dbConfigHcg.getTestQuery());

        return atomikosDataSourceBean;
    }

    @Bean(name = "hcgSqlSessionFactory")
    public SqlSessionFactory hcgSqlSessionFactory(@Qualifier("hcgDataSource") DataSource hcgDataSource)throws Exception{
        SqlSessionFactoryBean  bean = new SqlSessionFactoryBean();
        bean.setDataSource(hcgDataSource);
        return  bean.getObject();
    }

    @Bean(name = "hcgSqlSessionTemplate")
    public SqlSessionTemplate hcgSqlSessionTemplate(@Qualifier("hcgSqlSessionFactory") SqlSessionFactory hcgSqlSessionFactory)throws Exception{
        return new SqlSessionTemplate(hcgSqlSessionFactory);
    }



}
